﻿using System;

namespace NeuralNetworkPCL
{
    class Neuron
    {
        double[] weights;
        int nbInputs;
        
        double output;
        internal double Output
        {
            get
            {
                return output;
            }
        }

        internal Neuron(int _nbInputs)
        {
            nbInputs = _nbInputs;
            output = Double.NaN;

            Random generator = new Random();

            weights = new double[(nbInputs + 1)];
            for (int i = 0; i < (nbInputs + 1); i++)
            {
                weights[i] = generator.NextDouble() * 2.0 - 1.0;
            }
        }

        internal double Evaluate(DataPoint _point)
        {
            double[] inputs = _point.Inputs;
            return Evaluate(inputs);
        }

        internal double Evaluate(double[] _inputs)
        {
            if (output.Equals(Double.NaN))
            {
                double x = 0.0;

                for (int i = 0; i < nbInputs; i++)
                {
                    x += _inputs[i] * weights[i];
                }
                x += weights[nbInputs];

                output = 1.0 / (1.0 + Math.Exp(-1.0 * x));
            }

            return output;
        }

        internal void Clear()
        {
            output = Double.NaN;
        }

        internal double Weight(int index)
        {
            return weights[index];
        }

        internal void AdjustWeight(int index, double value)
        {
            weights[index] = value;
        }
    }
}
